import { ref } from 'vue'

// Toast 消息类型
const TOAST_TYPES = {
  success: 'success',
  error: 'danger',
  warning: 'warning',
  info: 'info'
}

// 全局 toast 状态
const toasts = ref([])
let toastId = 0

export function useToast() {
  const showToast = (message, type = 'info', duration = 3000) => {
    const id = ++toastId
    const toast = {
      id,
      message,
      type: TOAST_TYPES[type] || TOAST_TYPES.info,
      show: true
    }
    
    toasts.value.push(toast)
    
    // 自动隐藏
    if (duration > 0) {
      setTimeout(() => {
        hideToast(id)
      }, duration)
    }
    
    return id
  }
  
  const hideToast = (id) => {
    const index = toasts.value.findIndex(toast => toast.id === id)
    if (index > -1) {
      toasts.value.splice(index, 1)
    }
  }
  
  const clearAllToasts = () => {
    toasts.value.splice(0)
  }
  
  return {
    toasts,
    showToast,
    hideToast,
    clearAllToasts
  }
}

// 全局 toast 组件
export function createToastContainer() {
  return {
    template: `
      <div class="toast-container position-fixed top-0 end-0 p-3" style="z-index: 1055;">
        <div 
          v-for="toast in toasts" 
          :key="toast.id"
          class="toast show"
          :class="\`bg-\${toast.type}\`"
          role="alert"
        >
          <div class="toast-header">
            <strong class="me-auto text-white">
              <i class="bi" :class="getToastIcon(toast.type)"></i>
              {{ getToastTitle(toast.type) }}
            </strong>
            <button 
              type="button" 
              class="btn-close btn-close-white" 
              @click="hideToast(toast.id)"
            ></button>
          </div>
          <div class="toast-body text-white">
            {{ toast.message }}
          </div>
        </div>
      </div>
    `,
    setup() {
      const { toasts, hideToast } = useToast()
      
      const getToastIcon = (type) => {
        const icons = {
          success: 'bi-check-circle',
          danger: 'bi-exclamation-triangle',
          warning: 'bi-exclamation-triangle',
          info: 'bi-info-circle'
        }
        return icons[type] || icons.info
      }
      
      const getToastTitle = (type) => {
        const titles = {
          success: '成功',
          danger: '错误',
          warning: '警告',
          info: '提示'
        }
        return titles[type] || titles.info
      }
      
      return {
        toasts,
        hideToast,
        getToastIcon,
        getToastTitle
      }
    }
  }
}